package com.haois.mp.wechat.handler;

import com.haois.mp.wechat.common.BusinessRemind;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.common.daomain.WxUser;
import com.haois.mp.database.module.offaccounts.service.UserFollowService;
import com.haois.mp.database.module.common.service.IUserTokenService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 订阅事件处理器
 */
@Component
public class SubscribeHandler extends AbstractHandler implements WxMpMessageHandler {
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    protected IUserTokenService iUserTokenService;
    @Value("${defined.wxmp.sys-openid}")
    private String sysOpenId;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        String content = this.execute(wxMpXmlMessage, wxMpService);
        return WxMpXmlOutMessage.TEXT()
                .fromUser(wxMpXmlMessage.getToUser())
                .toUser(wxMpXmlMessage.getFromUser())
                .content(content).build();
    }

    @Override
    public String execute(WxMpXmlMessage wxMpXmlMessage, WxMpService wxMpService) throws WxErrorException {
        String content = "欢迎订阅MobileGroup微信端！" + "\n" +
                "\n" +
                "华工广州学院用户，请使用学号登录。" + "\n" +
                "华软集团用户，请使用企业邮箱登录。";
        String openId = wxMpXmlMessage.getFromUser();
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openId);
        userFollowService.syncWxMpUser(new WxUser(wxMpUser));

        UserToken userToken = iUserTokenService.findByOpenId(openId, MpTypeEnum.OFFACCOUNTS.getType());
        if (userToken == null) {
            userFollowService.updateUser(openId, null, "关注");
        } else {
            userFollowService.updateUser(openId, userToken.getUserId(), "重新关注");
        }
        BusinessRemind.remindSubByWx(wxMpService, wxMpUser, sysOpenId);
        return content;
    }
}
